<?php
/**
 * Created by a front-end programmer.
 * User: Xwen
 * Date: 2018/2/24
 * Time: 16:29
 * Mail:lauwencn@gmail.com
 */
class CommonController extends Controller{
    private $ignore_urls = [
        __APP__."?c=Authority&m=checkUserName",
        __APP__."?c=Authority&m=checkEditUserName",
        __APP__."?c=Authority&m=getParentsIdByLevel",
        __APP__."?c=Index&m=index",
    ];
    public function __init(){
        if(!isset($_SESSION['uid']) || !isset($_SESSION['username'])){
            go(__APP__.'?c=Login');
        }
        if(isset($_SESSION['expiration']) && isset($_SESSION['uid']) && isset($_SESSION['username'])){
            if($_SESSION['expiration']<time()){
                unset($_SESSION['expiration']);
                unset($_SESSION['uid']);
                unset($_SESSION['username']);
                header('Location:'.__APP__.'?c=Login&m=out');
                exit(0);
            }else{
                $_SESSION['expiration'] = time() + C('EXPIRATION');
            }
        }
        $urls = $this->getUserAccess($_SESSION['uid']);
        $url = __APP__."?c=".CONTROLLER."&m=".METHOD;
        $urls = array_merge($urls, $this->ignore_urls);
//        if($_SESSION['is_admin']) $urls = array_merge($urls, $this->ignore_urls);
        if(!in_array($url, $urls)) $this->error('你无权访问该页面,请联系管理员开通！');
    }
    public function getUserAccess($uid){
        $ur = K("UserRole")->get_all_cu($uid);
        $access = array();
        foreach ($ur as $v){
            $ra = K("RoleAccess")->get_all_cr($v['rid']);
            $rid = array_column($ra, 'aid');
            $access = array_unique(array_merge($access, $rid));
        }
        $urls = array();
        foreach ($access as $v){
            $info = K("Access")->get_one_ca($v);
            $info = __APP__."?c=".$info['control']."&m=".$info['method'];
            array_push($urls, $info);
        }
        return $urls;
    }
}//endclass
?>